<template>
<el-container style="display: flex; justify-content: center; height: 100%">
        <el-card class="box-card">
            <!-- 表格区域 -->
            <el-table :data="projectstaff" border style="width: 100%">
              <el-table-column label="项目名" width="150">
                    <template #default="{ row }">
                        <span>{{ projectname(row.projectid) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="参报人员" width="150">
                    <template #default="{ row }">
                        <div v-for="staff,index in row.userIds" :key="index">
                        <p>{{ username(staff) }}</p>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="申报难度">
                    <template #default="{ row }">
                        <div v-for="routineid,index in row.routine" :key="index">
                        <p style="float: left;">申报 {{index+1}}:[{{ routineid.content }}({{ routineid.code }}){{ routineid.score }}]</p>&nbsp;&nbsp;<el-button  type="primary" @click="operateroutineone(row.routine[index])" >操作</el-button>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="申报难度" width="150">
                    <template #default="{ row }">
                        <el-button @click="handleSubmit(row.routineid)" >删除所有申报</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </el-container>
    <el-dialog title="操作团队" v-model="dialogVisible" width="30%" @close="dialogVisible = false">
    <el-form :model="routineone">
      <el-form-item label="申报内容">
        <el-input v-model="routineone.content" placeholder="请输入申报内容"></el-input>
      </el-form-item>
      <el-form-item label="申报编码">
        <el-input v-model="routineone.code" placeholder="请输入申报编码"></el-input>
      </el-form-item> 
      <el-form-item label="申报分值">
        <el-input v-model="routineone.score" placeholder="请输入申报分值"></el-input>
      </el-form-item>
    </el-form>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit">提交修改</el-button>
      <el-button type="primary" @click="handleSubmitdelete">删除编码</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { ref,onMounted } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';

const route = useRoute();

const routine = ref([]);
const teamid = route.params.id;
const token = localStorage.getItem('adminToken');
const projectstaff = ref([]);
const projects = ref([]);
const staffs = ref([]);
const routineone = ref([]);
const dialogVisible = ref(false);

// 获取队伍报名项目以及人员申报信息
async function fetchProjectData() {
    try{
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/teamstaff/staff/project/${teamid}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });      
    projectstaff.value = response.data.staffs; 
    routine.value = projectstaff.value.map(item => item.routine);    
  } catch (error) {
    console.log(error);
  }
}

// 获取项目名称
async function fetchProjectdetail() {
    try{
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/project`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    projects.value = response.data.projects;
  } catch (error) {
    console.log(error);
  }
}

// 获取队伍成员信息
async function fetchStaffData() {    
    try{
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/teamstaff/staff/${teamid}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });        
    staffs.value = response.data.staffs; 
  } catch (error) {
    console.log(error);
  }
}

// 通过id获取项目名
function projectname(id) {
    const project = projects.value.find(item => item.id === id);
    return project ? project.projectName : '';
}

// 根据id获取用户名
function username(id) {
    const staffid = parseInt(id);
    const staff = staffs.value.find(staff => staff.id === staffid);
    return staff ? staff.id + staff.userName : '';
}

// 根据id获取申报内容的某一条
async function operateroutineone(routine){
  dialogVisible.value = true;
  routineone.value = routine;  
}

// 提交修改申报
async function submitEdit(){
  const routineadd = routineone.value;
  try{
    const response =await axios.put(`http://back1.idcfengye.com:15173/competition/teamstaff/revisestaff/one`, routineadd,{
      headers:{
        'Authorization': `Bearer ${token}`
      }
    })
    if(response.data.success){
      ElMessage.success('修改成功');
    }
  }catch(error){
    ElMessage.error('修改失败');
  }
}

//删除一条申报
async function deleteRoutineone() {
  const id = routineone.value.id;
  console.log(id);

  try {
    const response = await axios.delete(`http://back1.idcfengye.com:15173/competition/teamproject/routien/${id}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    if (response.data.success) {
      ElMessage.success('删除成功');
      dialogVisible.value = false;
    } 
  } catch (error) {
    console.log(error);
    ElMessage.error('删除失败：' + error.message);
  }
}

//删除一个项目所有的申报的再确认框
const handleSubmitdelete = async (routineid) => {
  ElMessageBox.confirm(`您确定要删除`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRoutineone();
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除'
    });
  });
};


//删除一个项目所有的申报
async function deleteroutine(routineid) {  
  try {
    const response = await axios.delete(`http://back1.idcfengye.com:15173/competition/teamproject/diifficutyid/${routineid}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    // 检查后端返回的成功状态
    if (response.data.success) {
      ElMessage.success('删除成功');
      fetchProjectData(); // 假设这是刷新项目数据的函数
    } else if (response.status === 404) {
      // 特别处理404状态码
      ElMessage.error('删除失败：找不到该记录');
    } else {
      // 处理其他可能的错误消息
      ElMessage.error(response.data.msg || '删除失败：未知错误');
    }
  } catch (error) {
    console.log(error);
    if (error.response && error.response.status === 404) {
      // 特别处理404状态码
      ElMessage.error('删除失败：找不到该记录');
    } else {
      // 处理其他可能的错误消息
      ElMessage.error('删除失败：' + (error.response ? error.response.data.msg : error.message));
    }
  }
}

// 删除团队再确认
const handleSubmit = async (routineid) => {
  ElMessageBox.confirm(`您确定要删除`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteroutine(routineid);
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除'
    });
  });
};


onMounted(() => {
  fetchStaffData();
  fetchProjectData();
  fetchProjectdetail();
})
</script>

<style scoped>

</style>